package com.xuecheng.content.listener;

import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.util.ObjectUtils;

/**
 * Created on 2021/04/11/10:04 周日
 *
 * @author Lantin
 */
@RocketMQTransactionListener
@Slf4j
public class CoursePubTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private CoursePubService coursePubService;

    @Autowired
    private CourseBaseService courseBaseService;


    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        byte[] payload = (byte[]) msg.getPayload();

        Long courseId = Long.valueOf(new String(payload));

        try {
            coursePubService.createOrModifyCoursePub(courseId);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("课程发布失败，课程id为 {}，异常为=>{}", courseId, e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {

        byte[] payload = (byte[]) msg.getPayload();

        Long courseId = Long.valueOf(new String(payload));

        CourseBase courseBase = courseBaseService.getById(courseId);

        String auditStatus = courseBase.getAuditStatus();

        if (ObjectUtils.nullSafeEquals(auditStatus, CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode())) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
